package com.scse.bms.web.admin;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.scse.bms.config.AppConfig;
import com.scse.bms.domain.DepotDTO;
import com.scse.bms.domain.RepositoryVO;
import com.scse.bms.domain.UserVO;
import com.scse.bms.entity.BookDO;
import com.scse.bms.entity.CommentDO;
import com.scse.bms.entity.RepositoryDO;
import com.scse.bms.service.RepositoryService;
import com.scse.bms.util.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * @Title: DepotController
 * @Author: 吴赠禹
 * @Date: 2021/3/4 16:32
 * @Version: 1.0
 * @Description: TODO
 */

@Slf4j
@RestController
public class DepotController {

    @Resource
    private AppConfig appConfig;

    @Autowired
    private RepositoryService repositoryService;

    /**
     * 上传Excel书单
     *
     * @param file
     * @return
     */
    @PostMapping("/book/upload/excel")
    public String uploadExcel(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        log.info("[uploadExcel] 导入书单Excel：" + fileName);
        // 指定存储目录（不存在则创建）
        String dirPath = appConfig.getExcelDir();
        boolean dirEmpty = FileUtil.isDirectory(dirPath);
        if (!dirEmpty) {
            FileUtil.mkdir(dirPath);
            log.info("[--------------] 文件目录不存在，创建一个！");
        }
        JSONObject bean = new JSONObject();
        log.info("开始导入书单！！");
        log.info("excel信息：" + file.toString() + " fileName " + fileName + " dirPath " + dirPath);
        try {

            file.transferTo(new File(dirPath + fileName));
            // 读取文件，批量插入数据
            List<RepositoryVO> list;
            if ("xls".equals(fileName.substring(fileName.lastIndexOf(".") + 1))) {
                list = ExcelUtil.parseXls(dirPath + fileName);
            } else {
                list = ExcelUtil.parseXlsx(dirPath + fileName);
            }
            int row = repositoryService.addBatch(list);
            bean.put("row", row);
            bean.put("msg", "success");
        } catch (Exception e) {
            log.info("[uploadExcel] 导入书单发生异常：" + e.getMessage());
        }
        return bean.toJSONString();

    }


    /**
     * 获取书库中的图书信息
     * @param pageNum
     * @param limit
     * @return
     */
    @GetMapping("/repository/list")
    public String getRepositoryList(@RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                    @RequestParam(required = false, defaultValue = "6") Integer limit) {
        log.info("[getRepositoryList] 获取电子书库的图书信息");

        Page<RepositoryDO> page = new Page<>(pageNum, limit);
        IPage<RepositoryDO> list = repositoryService.getAll(page);
        long total = list.getTotal();
        List<RepositoryDO> records = list.getRecords();
        JSONObject bean = new JSONObject();
        bean.put("code", 0);
        bean.put("msg", "success");
        bean.put("count", total);
        bean.put("data", records);
        log.info("[getRepositoryList] 返回的电子书库图书信息：" + records.toString());
        return bean.toString();
    }


    /**
     * 通过审核，加入图书
     * @param repositoryVO
     * @return
     */
    @PostMapping("/depot/check")
    public Integer check(@RequestBody RepositoryVO repositoryVO) {
        // 审核图书，将书库中的记录加入图书列表，然后删除书库中的记录
        int row = repositoryService.addIntoBook(repositoryVO.getId());
        if (row != 0) {
            // 删除书库中的记录
            repositoryService.removeById(repositoryVO.getId());
        }
        return row;
    }


    @PostMapping("/depot/checkBatch")
    public String checkBatch(@RequestBody DepotDTO depotDTO) {
        log.info("[checkBatch] 书库图书批量上架：" + depotDTO.getIdList().toString() + " " + depotDTO.getItemList().toString());
        // 先批量加入书架
        int addRow = repositoryService.addIntoBookrackBatch(depotDTO.getItemList());
        // 然后删除书库记录
        int delRow = repositoryService.deleteBatch(depotDTO.getIdList());
        JSONObject bean = new JSONObject();
        bean.put("row", addRow);
        bean.put("code", delRow);
        log.info("[checkBatch] 批量上架图书结果：" + bean.toJSONString());
        return bean.toString();
    }


    /**
     * 批量删除书库中的图书
     * @param depotDTO
     * @return
     */
    @PostMapping("/depot/deleteBatch")
    public Integer deleteBatch(@RequestBody DepotDTO depotDTO) {
        log.info("[deleteBatch] 接受参数：" + depotDTO.getIdList().toString());
        return repositoryService.deleteBatch(depotDTO.getIdList());
    }

    /**
     * 删除书库中的书
     * @param repositoryVO
     * @return
     */
    @PostMapping("/depot/delete")
    public Boolean delete(@RequestBody RepositoryVO repositoryVO) {
        boolean result = repositoryService.removeById(repositoryVO.getId());
        return result;
    }


    /**
     * 管理员预览PDF
     * @param id 改为通过ID预览
     * @return
     */
    @GetMapping("/admin/preview")
    public void preview(@RequestParam("id") Integer id,
                        HttpSession session, HttpServletRequest request,
                        HttpServletResponse response) throws Exception {
        UserVO user = (UserVO) session.getAttribute("loginUser");
        log.info("[preview] 管理员：{} 请求预览书库中ID：{} 的图书。", user.getId(), id);
        RepositoryDO repositoryDO = repositoryService.getById(id);
        String fileName = repositoryDO.getSrc();
        System.out.println("[preview] 获取到的文件名是:" + fileName + " 元组：" + repositoryDO);
        // 创建文件对象
        File file = new File(fileName);
        log.info("[preview] fileName:{}", fileName);
        // 设置响应头和内容类型
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "inline;fileName=" + fileName);
        // 通过文件流读取文件
        InputStream in = new FileInputStream(file);
        // 获取response对象的输出流
        OutputStream out = response.getOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        // 循环取出流中的数据
        while ((len = in.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }

    }


}
